package com.xinqi.modules.third.controller;

import com.xinqi.common.core.utils.MessageUtils;
import com.xinqi.common.base.response.R;
import com.xinqi.common.core.utils.StringUtils;
import com.xinqi.common.core.web.controller.BaseController;
import com.xinqi.modules.third.file.dto.req.FileUrlQueryDTO;
import com.xinqi.modules.third.service.ISysOssService;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 文件上传 控制层
 * @author dgyu
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/oss")
public class SysOssController extends BaseController {

    private final ISysOssService iSysOssService;

    /**
     * 获取阿里云OSS凭证
     */
    @PostMapping("/policy")
    public R<Map<String, String>> findOssPolicy() {
        return R.data(iSysOssService.findOssPolicy());
    }

    /**
     * 阿里文件删除
     */
    @DeleteMapping("/delete")
    public R<String> delete(String url) {
        if (iSysOssService.deleteFile(url)) {
            return R.ok(MessageUtils.message("common.new.del.success"));
        } else {
            return R.fail(MessageUtils.message("common.new.del.fail"));
        }

    }

    /**
     * 文档获取在线预览地址接口
     */
    @PostMapping("/onlinepreview")
    public R<String> onlinePreview(@RequestBody FileUrlQueryDTO req, HttpServletRequest request) throws Exception {
        String reviewUrl = iSysOssService.onlinePreview(req.getUrl());
        if (StringUtils.isEmpty(reviewUrl)) {
            return R.error("获取预览地址失败");
        } else {
            String url = request.getRequestURL().toString();
            if (StringUtils.isNotEmpty(url) && url.startsWith("https")) {
                reviewUrl = reviewUrl.replace("http://", "https://");
            }
            return R.ok("获取预览地址成功", reviewUrl);
        }
    }

}
